package top.zhangjianyong.blog.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.zhangjianyong.blog.entity.po.IpInfo;
import top.zhangjianyong.blog.mapper.IpInfoMapper;
import top.zhangjianyong.blog.service.IpInfoService;
import top.zhangjianyong.blog.utils.GeoIP2Util;
import java.time.LocalDateTime;

/**
 * @author zhangjianyong
 * @since 2025/7/26 15:11
 */
@Slf4j
@Service
public class IpInfoServiceImpl extends ServiceImpl<IpInfoMapper, IpInfo>
    implements IpInfoService {

    @Override
    public void saveOrUpdate(String ip) {
        if (ip == null || ip.trim().isEmpty()) {
            return;
        }

        try {
            // 获取GeoIP2信息
            IpInfo ipInfo = new IpInfo();
            ipInfo.setIp(ip);
            ipInfo.setGeoIP2Info(GeoIP2Util.getIpInfo(ip));

            // 检查IP是否已存在
            IpInfo existingIpInfo = lambdaQuery()
                .eq(IpInfo::getIp, ip)
                .eq(IpInfo::getIsDel, 0)
                .one();

            if (existingIpInfo != null) {
                ipInfo.setId(existingIpInfo.getId());
                this.updateById(ipInfo);
                //单独更新访问次数
                this.incrementQueryCount(ipInfo.getId());
            } else {
                ipInfo.setIsDel(0);
                ipInfo.setQueryCount(1);
                ipInfo.setLastQueryTime(LocalDateTime.now());
                this.save(ipInfo);
            }
        } catch (Exception e) {
            log.error("保存或更新IP信息失败: {}", ip, e);
        }
    }


    private void incrementQueryCount(Long id) {
        if (null == id) return;
        lambdaUpdate()
            .eq(IpInfo::getId, id)
            .setSql("query_count = query_count + 1")
            .update();
    }
}
